package com.example.datlichkham;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.res.Resources;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.example.adapter.BacSiAdapter;
import com.example.adapter.ChuyenKhoaAdapter;
import com.example.adapter.LichKhamAdapter;
import com.example.adapter.LichKhamArrayAdapter;
import com.example.database.BacsiTB;
import com.example.database.ChuyenkhoaTB;
import com.example.database.LichkhamTB;
import com.example.dto.Bacsi;
import com.example.dto.Chuyenkhoa;
import com.example.dto.Lichkham;


public class Datlichhen extends ActionBarActivity {
    Spinner spinnerKhoa;
    Spinner  spinnerBacSi;
    Spinner spinnerBv;
    String arrBv[]={"Bệnh viện Đà Nẵng"};
    Button btnTimlich,btnDatlich,btnTimbacsi;
    Button btntrove4;
    TextView txtDate,txtTime;
    ImageButton btnDate,btnTime;
    ArrayList<DateTime>arr=new ArrayList<DateTime>();
    ArrayAdapter<DateTime>adapter2=null;
    ListView lvCv;
    Calendar cal;
    Date date;
    Date hour;
    EditText txtc,txtd;
    ListView listview;
    public  ArrayList<Chuyenkhoa> arrchuyenkhoa = new ArrayList<Chuyenkhoa>();
    TextView output = null;
    BacSiAdapter adapter1;
    ChuyenKhoaAdapter adapter;
    LichKhamArrayAdapter adapterDL;
    int valuemaChuyenkhoa = 0;
    int valuemaBacSi = 0;
    String valueNgay = "";
    String valueGio = "";
    Datlichhen activity = null;
    public  ArrayList<Bacsi> arrbacsi = new ArrayList<Bacsi>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_datlichhen);
        
        btnTimbacsi = (Button)findViewById(R.id.btnTimBs);
        btnTimbacsi.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            	valueNgay = txtDate.getText().toString();
            	valueGio = txtTime.getText().toString();
                getDataForLichkham1(valuemaChuyenkhoa, valueNgay,valueGio);
            }
        });
        
        btnTimlich = (Button)findViewById(R.id.btnTimlich);
        btnTimlich.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            	valueNgay = txtDate.getText().toString();
                getDataForLichkham(valuemaChuyenkhoa, valuemaBacSi,valueNgay);
            }
        });

        spinnerKhoa = (Spinner)findViewById(R.id.spinnerKhoa);
        ArrayList<Chuyenkhoa> arrChuyenKhoa = new ArrayList<Chuyenkhoa>();
        String ma1 = "0";
        String ten1 = "Chọn Khoa";
        Chuyenkhoa khoa1 = new Chuyenkhoa(ma1, ten1);
        arrChuyenKhoa.add(khoa1);
        String query = "Select * from TbChuyenkhoa";
        ChuyenkhoaTB clsckTB = new ChuyenkhoaTB(this);
        Cursor cusor = clsckTB.getInforChuyenkhoa(query);
        if(cusor != null)
        {
            cusor.moveToFirst();
            while (cusor.isAfterLast()==false) {
                String maKhoa = cusor.getString(0);
                String tenKhoa = cusor.getString(1);
                Chuyenkhoa clskhoa = new Chuyenkhoa(maKhoa, tenKhoa);
                arrChuyenKhoa.add(clskhoa);
                cusor.moveToNext();
            }
            cusor.close();
        }
        adapter = new ChuyenKhoaAdapter(this, R.layout.chuyenkhoa_rows, arrChuyenKhoa);
        spinnerKhoa.setAdapter(adapter);
        spinnerKhoa.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parentView, View v, int position, long id) {
                getDataForBacSi(position);
                Chuyenkhoa chuyenkhoa = (Chuyenkhoa)spinnerKhoa.getItemAtPosition(position);
                valuemaChuyenkhoa = Integer.parseInt(chuyenkhoa.getId());
                Log.i("valuemaChuyenkhoa",valuemaChuyenkhoa+"");
            }
            @Override
            public void onNothingSelected(AdapterView<?> parentView) {
            }
        });
        
        spinnerBacSi = (Spinner)findViewById(R.id.spinnerBs);
        getDataForBacSi(0);
        
        spinnerBv = (Spinner) findViewById(R.id.spinnerBv);
        ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,
                arrBv
        );
        adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerBv.setAdapter(adapter2);
        

        listview = (ListView)findViewById(R.id.listLichkham);
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {

                int itemPosition = position;

                String itemValue = (String) listview.getItemAtPosition(position);

                Toast.makeText(getApplicationContext(),
                        "Position :" + itemPosition + "  ListItem : " + itemValue, Toast.LENGTH_LONG)
                        .show();
            }
        });
        getFormWidgets();
        getDefaultInfor();
        addEventFormWidgets();
//        getDataForLichkham(0, 0);

    }
    
    public void getDataForBacSi(int valueMaKhoa)
    {
        ArrayList<Bacsi> arrBacSi = new ArrayList<Bacsi>();
        String query1 ;
        if(valueMaKhoa==0)
        {
            query1 ="Select * from TbBacsi";
        }
        else{
            query1 = "Select * from TbBacsi where MaKhoa = "+valueMaKhoa+"";
        }
        BacsiTB clsbsTB = new BacsiTB(this);
        Cursor cusor1 = clsbsTB.getInforBacsi(query1);
        if(cusor1 != null)
        {
            cusor1.moveToFirst();
            while (cusor1.isAfterLast()==false) {
                String maBacsi = cusor1.getString(0);
                String tenBacsi = cusor1.getString(1);
                String maKhoa = cusor1.getString(2);
                Bacsi clsbacsi = new Bacsi(maBacsi, tenBacsi,maKhoa);
                arrBacSi.add(clsbacsi);
                cusor1.moveToNext();
            }
            cusor1.close();
        }
        adapter1 = new BacSiAdapter(this, R.layout.bacsi_rows, arrBacSi);
        spinnerBacSi.setAdapter(adapter1);
        spinnerBacSi.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parentView, View v, int position, long id) {
//                String txtBsRow    = ((TextView) v.findViewById(R.id.txtBsRow)).getText().toString();
                Bacsi bacSi = (Bacsi)spinnerBacSi.getItemAtPosition(position);
                valuemaBacSi = Integer.parseInt(bacSi.getMaBacsi());
                Log.i("valuemaBacSi",valuemaBacSi+"");
            }
            @Override
            public void onNothingSelected(AdapterView<?> parentView) {
            }

        });
    }
    public void getDataForLichkham(int valuemaChuyenkhoa,int valuemaBacsi,String valueNgay)
    {
        ArrayList<Lichkham> arrDatlich = new ArrayList<Lichkham>();
        String queryDL="";
        if(valuemaChuyenkhoa==0 && valuemaBacsi==0 && valueNgay.equals(""))
        {
            queryDL ="Select * from TbLichkham";
        }
        else
        {
            queryDL = "SELECT MaLichkham,TenChuyenkhoa,TenBacsi,Ngay,Gio,TrangThai FROM " +
                    "(TbLichkham INNER JOIN TbBacsi ON TbLichkham.MaBacsi=TbBacsi.MaBacsi) " +
                    "INNER JOIN TbChuyenkhoa ON TbLichkham.MaChuyenkhoa=TbChuyenkhoa.MaChuyenkhoa " +
                    " WHERE TbBacsi.MaBacsi="+valuemaBacsi+" and TbChuyenkhoa.MaChuyenkhoa = "+valuemaChuyenkhoa+" and TbLichkham.Ngay = '"+valueNgay+"' and " +
                    "TbLichkham.TrangThai=0";
        }
        LichkhamTB clsLKTB = new LichkhamTB(this);
        Cursor cusorLK = clsLKTB.getInforLichkham(queryDL);
        if(cusorLK != null)
        {
            cusorLK.moveToFirst();
            while (cusorLK.isAfterLast()==false) {
                String maLichKham = cusorLK.getString(0);
                String tenChuyenkhoa = cusorLK.getString(1);
                String tenBacsi = cusorLK.getString(2);
                String Ngay = cusorLK.getString(3);
                String Gio = cusorLK.getString(4);
                String TrangThai = cusorLK.getString(5);
                
                Lichkham clsDL = new Lichkham();
                clsDL.setMaLichkham(maLichKham);
                clsDL.setTenChuyenkhoa(tenChuyenkhoa);
                clsDL.setTenBacsi(tenBacsi);
                clsDL.setNgay(Ngay);
                clsDL.setGio(Gio);
                clsDL.setTrangThai(TrangThai);
                arrDatlich.add(clsDL);
                cusorLK.moveToNext();
            }
            cusorLK.close();
        }
        adapterDL = new LichKhamArrayAdapter(this, R.layout.listview_rows, arrDatlich);
        listview.setAdapter(adapterDL);

        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(Datlichhen.this, "qua day", Toast.LENGTH_SHORT).show();
            }
        });
    }
    public void getDataForLichkham1(int valuemaChuyenkhoa,String valueNgay,String valueGio)
    {
        ArrayList<Lichkham> arrTimBS = new ArrayList<Lichkham>();
        String queryTimBS="";
        if(valuemaChuyenkhoa==0 && valueNgay.equals("") && valueGio.equals(""))
        {
        	queryTimBS ="Select * from TbLichkham";
        }
        else
        {

        	queryTimBS = "SELECT MaLichkham,TenChuyenkhoa,TenBacsi,Ngay,Gio,TrangThai FROM " +
                    "(TbLichkham INNER JOIN TbBacsi ON TbLichkham.MaBacsi=TbBacsi.MaBacsi) " +
                    "INNER JOIN TbChuyenkhoa ON TbLichkham.MaChuyenkhoa=TbChuyenkhoa.MaChuyenkhoa " +
                    " WHERE TbChuyenkhoa.MaChuyenkhoa = "+valuemaChuyenkhoa+" and TbLichkham.Ngay = '"+valueNgay+"' and TbLichkham.Gio = "+valueGio+" and " +
                    "TbLichkham.TrangThai=0";
        	
        }
        LichkhamTB clsLKTB = new LichkhamTB(this);
        Cursor cusorLK = clsLKTB.getInforLichkham(queryTimBS);
        if(cusorLK != null)
        {
            cusorLK.moveToFirst();
            while (cusorLK.isAfterLast()==false) {
                String maLichKham = cusorLK.getString(0);
                String tenChuyenkhoa = cusorLK.getString(1);
                String tenBacsi = cusorLK.getString(2);
                String Ngay = cusorLK.getString(3);
                String Gio = cusorLK.getString(4);
                String TrangThai = cusorLK.getString(5);
                
                Lichkham clsDL = new Lichkham();
                clsDL.setMaLichkham(maLichKham);
                clsDL.setTenChuyenkhoa(tenChuyenkhoa);
                clsDL.setTenBacsi(tenBacsi);
                clsDL.setNgay(Ngay);
                clsDL.setGio(Gio);
                clsDL.setTrangThai(TrangThai);
                arrTimBS.add(clsDL);
                cusorLK.moveToNext();
            }
            cusorLK.close();
        }
        Resources resDL = getResources();
        LichKhamAdapter adapterTimBS = new LichKhamAdapter(this, R.layout.bacsi_rows, arrTimBS);
        spinnerBacSi.setAdapter(adapterTimBS);
        spinnerBacSi.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parentView, View v, int position, long id) {
                Bacsi bacSi = (Bacsi)spinnerBacSi.getItemAtPosition(position);
                valuemaBacSi = Integer.parseInt(bacSi.getMaBacsi());
                Log.i("valuemaBacSi",valuemaBacSi+"");
            }
            @Override
            public void onNothingSelected(AdapterView<?> parentView) {
            }
        });
    }
    public void setListData()
    {

        for (int i = 0; i < 11; i++) {
            final Lichkham arr3 = new Lichkham();
            /******* Firstly take data in model object ******/
            arr3.setMaLichkham(""+i);

            /******** Take Model Object in ArrayList **********/
//            arrlichkham.add(arr3);
        }

    }
    public void getFormWidgets()
    {
        txtDate=(TextView) findViewById(R.id.txtDate);
        txtTime=(TextView) findViewById(R.id.txtTime);
        btnDate=(ImageButton) findViewById(R.id.btnDate);
        btnTime=(ImageButton) findViewById(R.id.btnTime);
        //Gán DataSource vào ArrayAdapter
        adapter2=new ArrayAdapter<DateTime>
                (this,android.R.layout.simple_list_item_1,arr);
    }

    public void getDefaultInfor()
    {
        //lấy ngày hiện tại của hệ thống
        cal=Calendar.getInstance();
        SimpleDateFormat dft=null;
        //Định dạng ngày / tháng /năm
        dft=new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault());
        String strDate=dft.format(cal.getTime());
        //hiển thị lên giao diện
        txtDate.setText(strDate);
        //Định dạng giờ phút am/pm
        dft=new SimpleDateFormat("hh:mm a",Locale.getDefault());
        String strTime=dft.format(cal.getTime());
        //Đưa lên giao diện
        txtTime.setText(strTime);
        //lấy giờ theo 24 để lập trình theo Tag
        dft=new SimpleDateFormat("HH:mm",Locale.getDefault());
        txtTime.setTag(dft.format(cal.getTime()));
        date=cal.getTime();
        hour=cal.getTime();
    }
    public void addEventFormWidgets()
    {
        btnDate.setOnClickListener(new MyButtonEvent());
        btnTime.setOnClickListener(new MyButtonEvent());

    }
    private class MyButtonEvent implements View.OnClickListener
    {
        @Override
        public void onClick(View v) {
            switch(v.getId())
            {
                case R.id.btnDate:
                    showDatePickerDialog();
                    break;
                case R.id.btnTime:
                    showTimePickerDialog();
                    break;

            }
        }

    }

    /**
     * Ham hien thi DatePicker dialog
     */
    public void showDatePickerDialog()
    {
        DatePickerDialog.OnDateSetListener callback=new DatePickerDialog.OnDateSetListener() {
            public void onDateSet(DatePicker view, int year,
                                  int monthOfYear,
                                  int dayOfMonth) {
                //Moi lan thay doi ngay thang nam thì cap nhat lai TextView Date
                
                //Luu vet lai bien ngay hoan thanh
                cal.set(year, monthOfYear, dayOfMonth);
                date=cal.getTime();
                if((monthOfYear+1)>10)
                {
                	txtDate.setText(
                            (dayOfMonth) +"/"+(monthOfYear+1)+"/"+year);
                }
                else
                {
                	txtDate.setText(
                            (dayOfMonth) +"/0"+(monthOfYear+1)+"/"+year);
                }
                
            }
        };
        //Cac lenh duoi nay xu ly ngay gio trong DatePickerDialog
        //Se giong voi tren TextView khi mo no len
        String s=txtDate.getText()+"";
        String strArrtmp[]=s.split("/");
        int ngay=Integer.parseInt(strArrtmp[0]);
        int thang=Integer.parseInt(strArrtmp[1])-1;
        int nam=Integer.parseInt(strArrtmp[2]);
        DatePickerDialog pic=new DatePickerDialog(
                Datlichhen.this,
                callback, nam, thang, ngay);
        pic.show();
    }
    /**
     * Ham hien thi TimePickerDialog
     */
    public void showTimePickerDialog()
    {
        TimePickerDialog.OnTimeSetListener callback=new TimePickerDialog.OnTimeSetListener() {
            public void onTimeSet(TimePicker view,
                                  int hourOfDay, int minute) {
                //Xu ly luu gio va AM,PM
                String s=hourOfDay +":"+minute;
                int hourTam=hourOfDay;
                if(hourTam>12)
                    hourTam=hourTam-12;
                txtTime.setText
                        (hourTam +":"+minute +(hourOfDay>12?" PM":" AM"));
                //Luu gio thuc vao tag
                txtTime.setTag(s);
                //luu vet lai gio vao hourFinish
                cal.set(Calendar.HOUR_OF_DAY, hourOfDay);
                cal.set(Calendar.MINUTE, minute);
                hour=cal.getTime();
            }
        };
        //Cac lenh duoi nay xu ly ngay gio trong TimePickerDialog
        //se giong voi tren TextView khi mo no len
        String s=txtTime.getTag()+"";
        String strArr[]=s.split(":");
        int gio=Integer.parseInt(strArr[0]);
        int phut=Integer.parseInt(strArr[1]);
        TimePickerDialog time=new TimePickerDialog(
                Datlichhen.this,
                callback, gio, phut, true);
        time.show();
    }

}





